package com.itheima.sh.web;

import com.itheima.sh.dao.DishMapper;
import com.itheima.sh.pojo.Dish;
import com.itheima.sh.uilts.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLSyntaxErrorException;

@WebServlet("/addDish")
public class AddDishServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1,解决post请求乱码问题
        request.setCharacterEncoding("utf-8");
        //2,获取请求数据
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String description = request.getParameter("description");

        //3,封装数据
        Dish dish = new Dish();
        dish.setName(name);
        dish.setPrice(Double.parseDouble(price));
        dish.setDescription(description);

        //4,调用mapper方法进行数据添加操作
        //4.1 获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        //4.2 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.3 获取代理对象
        DishMapper dishMapper = sqlSession.getMapper(DishMapper.class);
        //4.4 调用方法添加数据
        dishMapper.addDish(dish);
        //5,提交事务
        sqlSession.commit();
        //6,响应添加数据成功标识
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("添加成功");
    }
}